package com.fingard.dsp.bank.directbank.cgbunion01;

import com.alibaba.fastjson.JSONObject;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.ICloseOrder;
import com.fingard.dsp.bank.reqrespobj.closeorder.CloseOrderState;
import com.fingard.dsp.bank.reqrespobj.closeorder.ReqCloseOrder;
import com.fingard.dsp.bank.reqrespobj.closeorder.RetAtsCloseOrder;
import com.fingard.text.StringHelper;

import java.util.HashMap;
import java.util.Map;

public class CGBUnion01CloseOrder extends CGB01UnifiedOrder implements ICloseOrder {

    @Override
    public RetAtsCloseOrder closeOrder(ReqCloseOrder p_req) {
        RetAtsCloseOrder retAts = new RetAtsCloseOrder(p_req.reqHeader);
        retAts.rdSeq = p_req.rdSeq;
        try {
            ActSetItem actItem = this.getBankConfig().getActSetItem(
                    p_req.ownAct, "");
            if (actItem != null) {
                Map<String, String> headMap = buildHeaderParam("closeJH", actItem);
                Map<String, Object> bodyMap = new HashMap<String, Object>();
                bodyMap.put("service", "unified.trade.close");
                bodyMap.put("version", "2.0");
                bodyMap.put("charset", "UTF-8");
                bodyMap.put("sign_type", "MD5");
                bodyMap.put("mch_id", actItem.merchantId);//商户appId
                bodyMap.put("out_trade_no", p_req.rdSeq);
                bodyMap.put("nonce_str", get_nonce_str());
                bodyMap.put("sign", "asdf");
                JSONObject closeOrder = new JSONObject();
                closeOrder.put("Header", headMap);
                closeOrder.put("Body", bodyMap);
                String returnStr = send(closeOrder, "closeJH", actItem);
                JSONObject resultObj = JSONObject.parseObject(returnStr);
                JSONObject resBody = resultObj.getJSONObject("Body");
                String result_code = resBody.getString("result_code");
                String err_code = resBody.getString("errorCode");
                String err_msg = resBody.getString("errorMsg");
                if (StringHelper.hasAnyChar(err_code)) {
                    retAts.respCode = "-1";
                    retAts.respInfo = err_msg;
                } else {
                    retAts.respCode = "0";
                    if ("0".equals(result_code)) {
                        retAts.closeState = CloseOrderState.Close_Success;
                    } else {
                        retAts.closeState = CloseOrderState.Close_Fail;
                    }
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号:[" + p_req.ownAct + "]相关商户配置信息!";
            }
        } catch (Exception ex) {
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            ex.printStackTrace();
            WriteBankLogLn(ex);
        }
        return retAts;
    }
}
